package pit.com.ordermobilesystem.a;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import pit.com.ordermobilesystem.R;
import pit.com.ordermobilesystem.http.HttpApiException;
import pit.com.ordermobilesystem.http.OrderSystemHttpService;
import pit.com.ordermobilesystem.http.Response;
import pit.com.ordermobilesystem.model.Order;
import pit.com.ordermobilesystem.tabhost.TabGroupActivity;
import pit.com.ordermobilesystem.util.OrderConstant;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class OrderActivity extends FragmentActivity implements OrderConstant {
	private EditText ed_NameCustomer;
	private EditText ed_MobileCustomer;
	private EditText ed_Description;
	private EditText ed_gio;
	private EditText tv_DateOrderod;

	private ImageView imv_nhaplai;
	private ImageView imv_guidi;

	private Calendar cal;
	private String NameOrder;
	private String strDate;
	private String strTime;
	private Spinner spinner;
	private Order order;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.orderfragment);

		ed_Description = (EditText) findViewById(R.id.ed_Descriptionod);
		ed_MobileCustomer = (EditText) findViewById(R.id.ed_MobileCustomerod);
		ed_NameCustomer = (EditText) findViewById(R.id.ed_NameCustomerod);
		ed_gio = (EditText) findViewById(R.id.ed_Gio);
		tv_DateOrderod = (EditText) findViewById(R.id.tv_DateOrderod);

		imv_nhaplai = (ImageView) findViewById(R.id.imv_lamlaiod);
		imv_guidi = (ImageView) findViewById(R.id.imv_guidiod);

		cal = Calendar.getInstance();
		SimpleDateFormat dft = null;
		dft = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
		strDate = dft.format(cal.getTime());
		tv_DateOrderod.setText(strDate);

		dft = new SimpleDateFormat("hh:mm", Locale.getDefault());
		strTime = dft.format(cal.getTime());
		// Ä‘Æ°a lÃªn giao diá»‡n
		ed_gio.setText(strTime);

		spinner = (Spinner) findViewById(R.id.spinner1);
		// sp_NameOrder.setOnItemSelectedListener((OnItemSelectedListener)
		// this);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, ArayNameOrder);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				NameOrder = ArayNameOrder[position];
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		// touch time will show dialog time

		ed_gio.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showTimePickerDialog();
			}
		});
		// Button lay ngay dat Order
		tv_DateOrderod.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showDatePickerDialog();
			}
		});
		// Button xoa het Nhap lai
		imv_nhaplai.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				ed_NameCustomer.setText("");
				ed_MobileCustomer.setText("");
				cal = Calendar.getInstance();
				SimpleDateFormat dft = null;
				dft = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
				strDate = dft.format(cal.getTime());
				strTime = dft.format(cal.getTime());
				tv_DateOrderod.setText(strDate);
				ed_Description.setText("");
			}
		});
		// Button gui Order di
		imv_guidi.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				/*
				 * nhap cac thong tin vao order sau do se goi chuyen len se vo ,
				 * o day thi da xong cong doan cho orderitem
				 */

				order = new Order();
				// for(int j =0; j< DetailsFragment.ListItem.size();j++){
				// OrderItem orderitem = new OrderItem();
				// orderitem= DetailsFragment.ListItem.get(j);
				// order.OrderItemList.add(orderitem);
				// }

				String st_NameCustomer = ed_NameCustomer.getText().toString();
				String st_MobileCustomer = ed_MobileCustomer.getText()
						.toString();

				if ((st_MobileCustomer.isEmpty() == true)
						|| (st_NameCustomer.isEmpty() == true)) {

					 Dialog();
//					Toast.makeText(getApplicationContext(),
//							"Xin quý khách điền đày đủ thông tin như trên",
//							Toast.LENGTH_LONG).show();

				} else {

					order.setNameOrder(NameOrder);
					order.setNameCustomer(st_NameCustomer);
					order.setMobileCustomer(Integer.valueOf(st_MobileCustomer));
					order.setDateOrder(ed_gio.getText().toString()
							+ tv_DateOrderod.getText().toString());
					// con cai giam gia phai lam sao ???

					order.setSumPrice(0);
					order.setDescription(ed_Description.getText().toString());

					new LoadingsaveOrder().execute("");

					// String strnow = "";
					// for (int i = 0; i < order.OrderItemList.size(); i++) {
					// OrderItem item = new OrderItem();
					// item = order.OrderItemList.get(i);
					// strnow = strnow + item.getNameItem() + " , ";
					// }
					// tv_comment.setText(strnow);

					cal = Calendar.getInstance();
					SimpleDateFormat dft = null;
					dft = new SimpleDateFormat("dd/MM/yyyy", Locale
							.getDefault());
					strDate = dft.format(cal.getTime());
					tv_DateOrderod.setText(strDate);
					ed_Description.setText("");
					ed_NameCustomer.setText("");
					ed_MobileCustomer.setText("");
					ed_gio.setText("");
				}

			}
		});

	}

	// saveOrder
	class LoadingsaveOrder extends AsyncTask<String, Void, Void> {

		private Exception exception = null;
		ProgressDialog dialog;
		Response respone;

		protected void onPreExecute() {
			TabGroupActivity parentActivity = (TabGroupActivity) getParent();
			dialog = new ProgressDialog(parentActivity);
			dialog.setMessage("Loading. Please wait...");
			dialog.setCanceledOnTouchOutside(false);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					LoadingsaveOrder.this.cancel(true);
					dialog.dismiss();
				}

			});
			dialog.show();

		}

		protected Void doInBackground(final String... args) {

			OrderSystemHttpService httpService = new OrderSystemHttpService(
					SERVER_HOST, PORT);
			try {

				httpService.saveOrder(order);

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				exception = e;
			} catch (HttpApiException e) {
				// TODO Auto-generated catch block
				exception = e;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				exception = e;
			}
			return null;
		}

		protected void onPostExecute(final Void unused) {
			dialog.cancel();

			if (exception == null) {
				if (order.getNameCustomer() != null) {// dieu kien thong bao

				} else {

				}
			} else {

			}

		}

	}

	static final String[] ArayNameOrder = new String[] {
			"PIZZA HUT MAXIMARK CỘNG HÒA", "PIZZA HUT DIAMOND PLAZA",
			"PIZZA HUT ĐỀ THÁM" };

	/*
	 * show dialog date co the thay doi ngay tuy chon
	 */
	public void showDatePickerDialog() {
		OnDateSetListener callback = new OnDateSetListener() {
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				strDate = (dayOfMonth) + "/" + (monthOfYear + 1) + "/" + year;
				tv_DateOrderod.setText(strDate);

				cal.set(year, monthOfYear, dayOfMonth);
			}
		};
		String s = tv_DateOrderod.getText() + "";
		String strArrtmp[] = s.split("/");
		int ngay = Integer.parseInt(strArrtmp[0]);
		int thang = Integer.parseInt(strArrtmp[1]) - 1;
		int nam = Integer.parseInt(strArrtmp[2]);
		TabGroupActivity parentActivity = (TabGroupActivity) getParent();
		DatePickerDialog pic = new DatePickerDialog(parentActivity, callback,
				nam, thang, ngay);
		pic.setTitle("chọn Ngày Đặt Bàn");
		pic.show();
	}

	// dialog time 24 h
	public void showTimePickerDialog() {
		OnTimeSetListener callback = new OnTimeSetListener() {
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				//
				String s = hourOfDay + ":" + minute;
				int hourTam = hourOfDay;
				if (hourTam > 12)
					hourTam = hourTam - 12;
				ed_gio.setText(hourTam + ":" + minute
						+ (hourOfDay > 12 ? " PM" : " AM"));
				//
				ed_gio.setTag(s);
				//
				cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
				cal.set(Calendar.MINUTE, minute);
			}
		};
		//
		String s = ed_gio.getText() + "";
		String strArr[] = s.split(":");
		int gio = Integer.parseInt(strArr[0]);
		int phut = Integer.parseInt(strArr[1]);
		TabGroupActivity parentActivity = (TabGroupActivity) getParent();
		TimePickerDialog time = new TimePickerDialog(parentActivity,
				callback, gio, phut, true);
		time.setTitle("chọn giờ Đặt Bàn");
		time.show();
	}

	// string of spiner
	@SuppressWarnings("deprecation")
	public void Dialog() {
		TabGroupActivity parentActivity = (TabGroupActivity)getParent();
		AlertDialog alertDialog1 = new AlertDialog.Builder(parentActivity).create();
		alertDialog1.setTitle("Cửa Hàng Pizza Hut");
		alertDialog1.setMessage("Vui lòng nhập tên bàn"
				+ "\nVui lòng nhập tên " + "\nVui lòng nhập số điện thoại");
		alertDialog1.setButton("OK", new DialogInterface.OnClickListener() {

			public void onClick(final DialogInterface dialog, final int which) {
				// Write your code here to execute after dialog
			}
		});

		alertDialog1.show();
	}
}
